자바 json, xml 형식의 http 요청 을 보 내 고 응답 response 내용 인 스 턴 스 를 읽 습 니 다.

3969 단어 자바
자바 에서 json, xml 형식의 http 요청 을 보 내 려 면 요청 을 받 은 서버 주소 (ip, 포트, 구체 적 인 디 렉 터 리) 를 확인 해 야 합 니 다.
그리고 연결 속성 정 보 를 설정 합 니 다.
요청 한 데이터 형식 (json 또는 xml)
필요 에 따라 서버 에 메시지 체 를 보 낼 지 여부 (http 헤드 만 보 낼 수 있 고 구체 적 인 정 보 는 보 내지 않 을 수 있 습 니 다) 에 따라 데이터 형식 은 설 정 된 http 헤드 정보 설정 형식 과 일치 해 야 합 니 다. 전송 과 서버 의 응답 에 대한 구체 적 인 정 보 를 보 려 면 http 패키지 도 구 를 사용 할 수 있 습 니 다. 예 를 들 어 http Analizer 등 소프트웨어 를 사용 하여 요청 데이터 형식 이 정확 한 지 확인 할 수 있 습 니 다.
구체 적 인 코드 는 다음 과 같 습 니 다 (요청 데이터 형식 은 json).
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import java.io.OutputStream;

 import java.net.HttpURLConnection;
import java.net.MalformedURLException;

 import java.net.URL;
 import org.json.JSONObject;
import org.json.JSONArray; 
 
public class AppAddTest {
 
    public static final String ADD_URL = "http://192.168.4.68:35357/v2.0/users";
 //   public static final String ADD_URL = "http://192.168.4.97:35357/v2.0/tokens";
    public static void appadd() throws IOException {
    	HttpURLConnection connection=null;
        try {
             //    
             URL url = new URL(ADD_URL);
             connection = (HttpURLConnection) url.openConnection();
             

             //  http    
             
             connection.setDoOutput(true);
             connection.setDoInput(true);
             connection.setRequestMethod("POST"); //           GET、POST、DELETE、INPUT http     
             connection.setUseCaches(false);
             connection.setInstanceFollowRedirects(true);
             
             //  http    
             connection.setRequestProperty("Content-Type","application/json");  //        json,     xml   
             //connection.setRequestProperty("Content-Type", "text/xml");   //        xml,
             connection.setRequestProperty("Accept","application/json");//            json,     xml   
//             connection.setRequestProperty("X-Auth-Token","xx");  //  http        ,           
             connection.connect();
 
             //       
             
            JSONObject user = new JSONObject();  
            user.put("name", "alice4");
            user.put("roles", "admin");
            user.put("enabled", "true");
            user.put("tenantId", "998abe42845e4f258da7e96b0d8335ec");
            user.put("password", "mypassword123");

            //      json  
            
            JSONObject obj = new JSONObject();
             obj.put("user",user);
             OutputStream out = connection.getOutputStream();                        
             out.write(obj.toString().getBytes());
             out.flush();
             out.close();
 
//                
             BufferedReader reader = new BufferedReader(new InputStreamReader(
                     connection.getInputStream()));
             String lines;
             StringBuffer sb = new StringBuffer("");
             while ((lines = reader.readLine()) != null) {
                 lines = new String(lines.getBytes(), "utf-8");
                 sb.append(lines);
             }
             System.out.println(sb);
             reader.close();
////                  
             connection.disconnect();
         } catch (MalformedURLException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         } catch (UnsupportedEncodingException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
 
    }

 
    public static void main(String[] args) throws IOException {
         appadd();
     }
 
}

좋은 웹페이지 즐겨찾기