2012-05-08 1 views
49

JavaのHttpURLConnectionオブジェクトで基本的なhttp認証を行っています。HttpURLConnectionオブジェクトからJSONを解析します。

 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でシンプルなプレーンテキストとHTMLでJSONオブジェクト、または文字列データを期待しています。応答を返した後にHttpURLConnectionからアクセスするにはどうすればよいですか?

+2

すべての2xx HTTPステータスコードが成功を示していることに注意してください。 – Fred

答えて

95

あなたは法の下に使用した生データを取得することができます。ところで、このパターンはJava 6用です。Java 7以降を使用している場合は、try-with-resources patternと考えてください。

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; 
} 

そして、あなたはこのように、指定されたクラスのオブジェクトへのJSONをマッピングするためGoogle Gsonで返された文字列を使用することができます。

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; 
    } 
} 

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

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

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

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

よろしく

+1

接続 'c'をどこで閉じることができますか? –

+0

もともと私はtry-with-resourcesを使ってこれをJava 7の方法で書いていましたが、誰かがjava 6を保つことに決めたので、接続の終了は最後に無視されました。しかし、はい、接続を閉じる必要があります。私はこれを後で編集します。 – kbec

+0

@kbec接続をどこで終了したのかまだ分かりません。これをあなたの答えに加えてください。 – confile

9

次の関数(ない鉱山ではなく、私はずっと前にそれを見つけた場所を確認してください)定義します。次に

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.... 
    } 
+0

'convertStreamToString'は、接続が途中で失われた場合、文字列が不完全であることを呼び出しコードに通知しません。一般的には、例外をバブルアップさせる方が良いです。 –

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表現を提供することだけです。

Here's an example using JSON-LIB

+0

入力を読み取る例外がある場合、入力バッファは閉じられません。 –

2

、あなたはHTTPエラー(400-5 **コード)の場合には、あなたのオブジェクトを解析したい場合は、 あなたは以下のコードを使用することができます(単に「getErrorStream」で「のgetInputStream」を置換します:

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(); 
1

この関数は、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); 
} 

はここと呼ばれ、我々は、我々が受け取ったJSONのうち、簡単なPOJOを作ってみるの文を次のようにApacheのライブラリClass.Andを使用してJSONの文字列形式を受け取ります。

​​

これは、jsonに付属している単純なJavaモデルクラスです。 パブリッククラス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を含めます。

関連する問題