65

HttpURLConnectionJavaのオブジェクトで基本的なhttp認証を行っています。

        URL urlUse = new URL(url);
        HttpURLConnection conn = null;
        conn = (HttpURLConnection) urlUse.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-length", "0");
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);
        conn.connect();

        if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
        {
            success = true;
        }

JSON オブジェクト、または有効な JSON オブジェクト形式の文字列データ、または有効な JSON である単純なプレーン テキストを含む HTML を期待しています。HttpURLConnection応答を返した後からアクセスするにはどうすればよいですか?

4

5 に答える 5

118

以下のメソッドを使用して生データを取得できます。ところで、このパターンは Java 6 用です。Java 7 以降を使用している場合は、try-with-resources パターンを検討してください。

public String getJSON(String url, int timeout) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
       if (c != null) {
          try {
              c.disconnect();
          } catch (Exception ex) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
          }
       }
    }
    return null;
}

そして、次のように、返された文字列をGoogle Gsonで使用して、JSON を指定されたクラスのオブジェクトにマップできます。

String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);

AuthMsg クラスのサンプルがあります。

public class AuthMsg {
    private int code;
    private String message;

    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

http://localhost/authmanager.phpによって返される JSON は次のようになります。

{"code":1,"message":"Logged in"}

よろしく

于 2012-05-08T15:24:37.297 に答える
11

次の関数を定義します(私のものではなく、ずっと前にどこで見つけたかわからない):

private static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        is.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
return sb.toString();

}

それで:

String jsonReply;
if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
    {
        success = true;
        InputStream response = conn.getInputStream();
        jsonReply = convertStreamToString(response);

        // Do JSON handling here....
    }
于 2012-05-08T14:48:04.597 に答える
3

さらに、http エラー (400-5** コード) の場合にオブジェクトを解析したい場合は、次のコードを使用できます: ('getInputStream' を 'getErrorStream' に置き換えるだけです:

    BufferedReader rd = new BufferedReader(
            new InputStreamReader(conn.getErrorStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();
    return sb.toString();
于 2014-06-16T11:58:21.610 に答える
2

JSON文字列は、呼び出したURLから返される応答の本文になります。したがって、このコードを追加します

...
BufferedReader in = new BufferedReader(new InputStreamReader(
                            conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) 
    System.out.println(inputLine);
in.close();

これにより、JSONがコンソールに返されるのを確認できます。不足しているのは、JSONライブラリを使用してそのデータを読み取り、Java表現を提供することだけです。

JSON-LIBを使用した例を次に示します

于 2012-05-08T14:48:24.887 に答える
0

この関数は、HttpResponse オブジェクトの形式で URL からデータを取得するために使用されます。

public HttpResponse getRespose(String url, String your_auth_code){
HttpClient client = new DefaultHttpClient();
HttpPost postForGetMethod = new HttpPost(url);
postForGetMethod.addHeader("Content-type", "Application/JSON");
postForGetMethod.addHeader("Authorization", your_auth_code);
return client.execute(postForGetMethod);
}

上記の関数はここで呼び出され、Apache ライブラリ クラスを使用して JSON の文字列形式を受け取ります。次のステートメントでは、受け取った json から単純な pojo を作成しようとします。

String jsonString     =     
EntityUtils.toString(getResponse("http://echo.jsontest.com/title/ipsum/content/    blah","Your_auth_if_you_need_one").getEntity(), "UTF-8");
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(JsonJavaModel .class, new    CustomJsonDeserialiser());
final Gson gson = gsonBuilder.create();
JsonElement json = new JsonParser().parse(jsonString);
JsonJavaModel pojoModel = gson.fromJson(
                    jsonElementForJavaObject, JsonJavaModel.class);

これは、着信 json 用の単純な Java モデル クラスです。public class JsonJavaModel{ 文字列の内容。文字列のタイトル。これはカスタム デシリアライザーです。

public class CustomJsonDeserialiserimplements JsonDeserializer<JsonJavaModel>         {

@Override
public JsonJavaModel deserialize(JsonElement json, Type type,
                                 JsonDeserializationContext arg2) throws    JsonParseException {
    final JsonJavaModel jsonJavaModel= new JsonJavaModel();
    JsonObject object = json.getAsJsonObject();

    try {
     jsonJavaModel.content = object.get("Content").getAsString()
     jsonJavaModel.title = object.get("Title").getAsString()

    } catch (Exception e) {

        e.printStackTrace();
    }
    return jsonJavaModel;
}

Gson ライブラリと org.apache.http.util.EntityUtils を含めます。

于 2015-05-13T11:48:33.613 に答える