如何在 android 中使用 HttpURLConnection 发送字符串
How to send String using HttpURLConnection in android
我需要向我的 Web 服务发送一个字符串,但我对如何使用 HttpURLConnection 发送字符串有疑问。
Obs:在字符串中 "result" 我有类似的东西:
{"sex":"Famale","nome":"Larissa Aparecida Nogueira","convenios":[{"convenio":2,"tipo":"Principal","number":"44551-1456-6678-3344"}],"user":"lari.ap","email":"lari.ap@yahoo.com.br","cell":"(19)98167-5569"}
以下是我的代码:
public UsuerService(Context context, String result) {
this.progressDialog = new ProgressDialog(context);
this.context = context;
this.result = result;
}
@Override
protected String doInBackground(String... params) {
String responseString = "";
try {
URL url = new URL(Constants.USUARIO + "/createUsuario");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null) {
response.append(inputLine);
}
result = response.toString();
bufferedReader.close();
} catch (Exception e) {
Log.d("InputStream", e.getMessage());
}
return null;
}
我有一个 Class 可以获取我的数据并将其解析为 JsonObject。
我需要了解如何使用 HttpURLConnection 为 Web 服务发送我的 object.toString()。
代码如下:
public String parserUsuarioJson(){
JSONObject object = new JSONObject();
try {
object.put(Constants.KEY_NAME, mUsuario.getNome());
object.put(Constants.KEY_EMAIL, mUsuario.getEmail());
object.put(Constants.KEY_USER, mUsuario.getUser());
object.put(Constants.KEY_PASS, mUsuario.getSenha());
object.put(Constants.KEY_SEX, mUsuario.getSexo());
object.put(Constants.KEY_CELLPHONE, mUsuario.getCelular());
JSONArray array = new JSONArray();
for(int i = 0; i < mUsuario.getUsuarioConvenios().size() ; i++){
JSONObject convenio = new JSONObject();
convenio.put(Constants.KEY_CONVENIO, mUsuario.getUsuarioConvenios().get(i).getConvenio().getId());
convenio.put(Constants.KEY_NUMBER, mUsuario.getUsuarioConvenios().get(i).getNumero());
convenio.put(Constants.KEY_TYPE, mUsuario.getUsuarioConvenios().get(i).getTipo());
array.put(convenio);
}
object.put(Constants.KEY_CONVENIOS, array);
} catch (JSONException e) {
Log.e("Register", e.getMessage());
}
return object.toString();
}
提前致谢。 :)
使用NameValuePairList发送数据。
尝试这样的事情...
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.USUARIO + "/createUsuario");
try {
// Add your key-value pair here
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("sex", "female"));
nameValuePairs.add(new BasicNameValuePair("nome", "Larissa Aparecida Nogueira"));
// set all other key-value pairs
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
用于使用 http post 通过网络发送 json 对象。
在此处传递 json 字符串
StringEntity se = new StringEntity(object.toString());
httpost.setEntity(se);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httpost);
别忘了捕获异常。
正在使用 httpurlConnection 发送 json 对象...
try {
//constants
URL url = new URL(Constants.USUARIO + "/createUsuario");
String yourJsonString = object.toString();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(yourJsonString.getBytes().length);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
conn.connect();
OutputStream os = new BufferedOutputStream(conn.getOutputStream());
os.write(yourJsonString.getBytes());
os.flush();
InputStream is = conn.getInputStream();
} finally {
//clean up
os.close();
is.close();
conn.disconnect();
}
据我了解,您想将字符串发送到 Web 服务。我在这里给你一个示例代码,我将一些字符串值发送到 web 服务。它的工作代码`
private class BackgroundOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params)
//Your network connection code should be here .
String response = postCall("Put your WebService url here");
return response ;
}
@Override
protected void onPostExecute(String result) {
//Print your response here .
Log.d("Post Response",result);
}
@Override
protected void onPreExecute() {}
@Override
protected void onProgressUpdate(Void... values) {}
}
public static String postCall(String uri) {
String result ="";
try {
//Connect
HttpURLConnection 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"));
//Call parserUsuarioJson() inside write(),Make sure it is returning proper json string .
writer.write(parserUsuarioJson());
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;
}
现在您可以使用以下代码从 activity 的 onCreate() 函数中调用上面的代码。
new BackgroundOperation().execute("");
注意:不要忘记在您的 manifest.xml
中提及以下许可
<uses-permission android:name="android.permission.INTERNET" />
注意:确保
1。 parserUsuarioJson() 正在返回正确的 json 字符串 .
2。您的网络服务正在运行。
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL(Constants.USUARIO + "/createUsuario");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setFixedLengthStreamingMode(result.getBytes().length);
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
httpURLConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
httpURLConnection.connect();
OutputStream os = new BufferedOutputStream(httpURLConnection.getOutputStream());
os.write(result.getBytes());
os.flush();
os = httpURLConnection.getOutputStream();
os.close();
httpURLConnection.disconnect();
} catch (Exception e) {
Log.d("InputStream", e.getMessage());
}
我需要向我的 Web 服务发送一个字符串,但我对如何使用 HttpURLConnection 发送字符串有疑问。
Obs:在字符串中 "result" 我有类似的东西:
{"sex":"Famale","nome":"Larissa Aparecida Nogueira","convenios":[{"convenio":2,"tipo":"Principal","number":"44551-1456-6678-3344"}],"user":"lari.ap","email":"lari.ap@yahoo.com.br","cell":"(19)98167-5569"}
以下是我的代码:
public UsuerService(Context context, String result) {
this.progressDialog = new ProgressDialog(context);
this.context = context;
this.result = result;
}
@Override
protected String doInBackground(String... params) {
String responseString = "";
try {
URL url = new URL(Constants.USUARIO + "/createUsuario");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = bufferedReader.readLine()) != null) {
response.append(inputLine);
}
result = response.toString();
bufferedReader.close();
} catch (Exception e) {
Log.d("InputStream", e.getMessage());
}
return null;
}
我有一个 Class 可以获取我的数据并将其解析为 JsonObject。 我需要了解如何使用 HttpURLConnection 为 Web 服务发送我的 object.toString()。
代码如下:
public String parserUsuarioJson(){
JSONObject object = new JSONObject();
try {
object.put(Constants.KEY_NAME, mUsuario.getNome());
object.put(Constants.KEY_EMAIL, mUsuario.getEmail());
object.put(Constants.KEY_USER, mUsuario.getUser());
object.put(Constants.KEY_PASS, mUsuario.getSenha());
object.put(Constants.KEY_SEX, mUsuario.getSexo());
object.put(Constants.KEY_CELLPHONE, mUsuario.getCelular());
JSONArray array = new JSONArray();
for(int i = 0; i < mUsuario.getUsuarioConvenios().size() ; i++){
JSONObject convenio = new JSONObject();
convenio.put(Constants.KEY_CONVENIO, mUsuario.getUsuarioConvenios().get(i).getConvenio().getId());
convenio.put(Constants.KEY_NUMBER, mUsuario.getUsuarioConvenios().get(i).getNumero());
convenio.put(Constants.KEY_TYPE, mUsuario.getUsuarioConvenios().get(i).getTipo());
array.put(convenio);
}
object.put(Constants.KEY_CONVENIOS, array);
} catch (JSONException e) {
Log.e("Register", e.getMessage());
}
return object.toString();
}
提前致谢。 :)
使用NameValuePairList发送数据。
尝试这样的事情...
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.USUARIO + "/createUsuario");
try {
// Add your key-value pair here
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("sex", "female"));
nameValuePairs.add(new BasicNameValuePair("nome", "Larissa Aparecida Nogueira"));
// set all other key-value pairs
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
用于使用 http post 通过网络发送 json 对象。
在此处传递 json 字符串
StringEntity se = new StringEntity(object.toString());
httpost.setEntity(se);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httpost);
别忘了捕获异常。
正在使用 httpurlConnection 发送 json 对象...
try {
//constants
URL url = new URL(Constants.USUARIO + "/createUsuario");
String yourJsonString = object.toString();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(yourJsonString.getBytes().length);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
conn.connect();
OutputStream os = new BufferedOutputStream(conn.getOutputStream());
os.write(yourJsonString.getBytes());
os.flush();
InputStream is = conn.getInputStream();
} finally {
//clean up
os.close();
is.close();
conn.disconnect();
}
据我了解,您想将字符串发送到 Web 服务。我在这里给你一个示例代码,我将一些字符串值发送到 web 服务。它的工作代码`
private class BackgroundOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params)
//Your network connection code should be here .
String response = postCall("Put your WebService url here");
return response ;
}
@Override
protected void onPostExecute(String result) {
//Print your response here .
Log.d("Post Response",result);
}
@Override
protected void onPreExecute() {}
@Override
protected void onProgressUpdate(Void... values) {}
}
public static String postCall(String uri) {
String result ="";
try {
//Connect
HttpURLConnection 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"));
//Call parserUsuarioJson() inside write(),Make sure it is returning proper json string .
writer.write(parserUsuarioJson());
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;
}
现在您可以使用以下代码从 activity 的 onCreate() 函数中调用上面的代码。
new BackgroundOperation().execute("");
注意:不要忘记在您的 manifest.xml
中提及以下许可<uses-permission android:name="android.permission.INTERNET" />
注意:确保
1。 parserUsuarioJson() 正在返回正确的 json 字符串 .
2。您的网络服务正在运行。
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL(Constants.USUARIO + "/createUsuario");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setFixedLengthStreamingMode(result.getBytes().length);
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
httpURLConnection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
httpURLConnection.connect();
OutputStream os = new BufferedOutputStream(httpURLConnection.getOutputStream());
os.write(result.getBytes());
os.flush();
os = httpURLConnection.getOutputStream();
os.close();
httpURLConnection.disconnect();
} catch (Exception e) {
Log.d("InputStream", e.getMessage());
}