Android에서 요청을 통해 JSON 개체를 전송하는 방법은 무엇입니까?
아래의 JSON 문자를 보내고 싶습니다.
{"Email":"aaa@tbbb.com","Password":"123456"}
웹 서비스에 접속하여 응답을 읽습니다.나는 JSON을 읽을 줄 안다.문제는 위의 JSON 개체가 변수 이름으로 전송되어야 한다는 것입니다.jason
.
안드로이드에서 어떻게 하면 될까요?요청 오브젝트 작성, 콘텐츠헤더 설정 등의 단계는 무엇입니까?
Apache HTTP Client를 사용하면 Android에서 json 개체를 쉽게 전송할 수 있습니다.여기 그 방법에 대한 코드 샘플이 있습니다.UI 스레드가 잠기지 않도록 네트워크 액티비티용으로 새 스레드를 생성해야 합니다.
protected void sendJson(final String email, final String pwd) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(URL);
json.put("email", email);
json.put("password", pwd);
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
} catch(Exception e) {
e.printStackTrace();
createDialog("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
Google Gson을 사용하여 JSON을 전송 및 검색할 수도 있습니다.
Android에는 HTTP 송수신용 특별한 코드가 없기 때문에 표준 Java 코드를 사용할 수 있습니다.Android와 함께 제공되는 Apache HTTP 클라이언트를 사용하는 것을 추천합니다.여기 HTTP POST에 사용한 코드 조각이 있습니다.
"jason"이라는 변수에서 개체를 보내는 것이 어떤 것과 관련이 있는지 모르겠습니다.서버가 정확히 무엇을 원하는지 모를 경우, 테스트 프로그램을 작성하여 필요한 형식을 알 때까지 서버에 다양한 문자열을 보내는 것을 고려해 보십시오.
int TIMEOUT_MILLISEC = 10000; // = 10 seconds
String postMessage="{}"; //HERE_YOUR_POST_STRING.
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost request = new HttpPost(serverUrl);
request.setEntity(new ByteArrayEntity(
postMessage.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);
public void postData(String url,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpClient httpclient = new DefaultHttpClient(myParams );
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(url.toString());
httppost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
HttpPost
는 Android API 레벨 22에서 권장되지 않습니다.그래서, 사용HttpUrlConnection
더 나아가기 위해서.
public static String makeRequest(String uri, String json) {
HttpURLConnection urlConnection;
String url;
String data = json;
String result = null;
try {
//Connect
urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.connect();
//Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
Android HTTP용 라이브러리는 다음 링크에 있습니다.
http://loopj.com/android-async-http/
간단한 요청은 매우 간단합니다.
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println(response);
}
});
JSON(크레딧을 https://github.com/loopj/android-async-http/issues/125)에 있는 'credit'으로 전송하려면:
// params is a JSONObject
StringEntity se = null;
try {
se = new StringEntity(params.toString());
} catch (UnsupportedEncodingException e) {
// handle exceptions properly!
}
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
client.post(null, "www.example.com/objects", se, "application/json", responseHandler);
모두 비동기식으로 Android와 잘 작동하며 UI 스레드에서 호출해도 안전합니다.responseHandler는 작성한 스레드(일반적으로 UI 스레드)에서 실행됩니다.JSON용 resonse Handler도 내장되어 있습니다만, Google gson을 사용하고 싶습니다.
이제부터는HttpClient
더 이상 사용되지 않습니다.현재 작업 코드는HttpUrlConnection
연결을 만들고 연결에서 및 읽기를 작성합니다.하지만 나는 발리를 사용하는 것을 선호했다.이 라이브러리는 Android AOSP에서 가져온 것입니다.나는 매우 사용하기 쉬웠다.JsonObjectRequest
또는JsonArrayRequest
이것만큼 간단한 것은 없다.OkHttpLibrary 사용
json을 만듭니다.
JSONObject requestObject = new JSONObject();
requestObject.put("Email", email);
requestObject.put("Password", password);
이렇게 보내주시면 됩니다.
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.addHeader("Content-Type","application/json")
.url(url)
.post(requestObject.toString())
.build();
okhttp3.Response response = client.newCall(request).execute();
public class getUserProfile extends AsyncTask<Void, String, JSONArray> {
JSONArray array;
@Override
protected JSONArray doInBackground(Void... params) {
try {
commonurl cu = new commonurl();
String u = cu.geturl("tempshowusermain.php");
URL url =new URL(u);
// URL url = new URL("http://192.168.225.35/jabber/tempshowusermain.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
JSONObject jsonObject=new JSONObject();
jsonObject.put("lid",lid);
DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
outputStream.write(jsonObject.toString().getBytes("UTF-8"));
int code = httpURLConnection.getResponseCode();
if (code == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
object = new JSONObject(stringBuffer.toString());
// array = new JSONArray(stringBuffer.toString());
array = object.getJSONArray("response");
}
} catch (Exception e) {
e.printStackTrace();
}
return array;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(JSONArray array) {
super.onPostExecute(array);
try {
for (int x = 0; x < array.length(); x++) {
object = array.getJSONObject(x);
ComonUserView commUserView=new ComonUserView();// commonclass.setId(Integer.parseInt(jsonObject2.getString("pid").toString()));
//pidArray.add(jsonObject2.getString("pid").toString());
commUserView.setLid(object.get("lid").toString());
commUserView.setUname(object.get("uname").toString());
commUserView.setAboutme(object.get("aboutme").toString());
commUserView.setHeight(object.get("height").toString());
commUserView.setAge(object.get("age").toString());
commUserView.setWeight(object.get("weight").toString());
commUserView.setBodytype(object.get("bodytype").toString());
commUserView.setRelationshipstatus(object.get("relationshipstatus").toString());
commUserView.setImagepath(object.get("imagepath").toString());
commUserView.setDistance(object.get("distance").toString());
commUserView.setLookingfor(object.get("lookingfor").toString());
commUserView.setStatus(object.get("status").toString());
cm.add(commUserView);
}
custuserprof = new customadapterformainprofile(getActivity(),cm,Tab3.this);
gridusername.setAdapter(custuserprof);
// listusername.setAdapter(custuserprof);
} catch (Exception e) {
e.printStackTrace();
}
}
언급URL : https://stackoverflow.com/questions/3027066/how-to-send-a-json-object-over-request-with-android
'programing' 카테고리의 다른 글
NodeJs 애플리케이션 및 모듈 전체에서 Mongodb에 대한 연결을 적절하게 재사용하는 방법 (0) | 2023.03.23 |
---|---|
ASP에서 파일을 다운로드합니다.Angular를 사용하는 NET Web API 메서드JS (0) | 2023.03.23 |
스냅샷을 생성할 때 Jest/Enzym ShowlowWrapper가 비어 있습니다. (0) | 2023.03.23 |
스프링 부트 내의 /info 엔드포인트에 프로그래밍 방식으로 추가하는 방법은 무엇입니까? (0) | 2023.03.23 |
UI 라우터를 사용하여 현재 상태 이름 노출 (0) | 2023.03.23 |