从android我希望将学生详细信息作为json String发送到服务器。 所以,我有: -
String url1 = "http://my ipaddress/AndroidProject/details";
List<Pair<String, String>> pairs = new ArrayList<>();
pairs.add(new Pair<>("details", JsonString));
URL url = new URL(url1);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
// POST the signup
try {
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8"));
writer.write(pairs.toString());
writer.flush();
writer.close();
os.close();
conn.connect();
}
catch (IOException ioe) {
//error display
}
而且,接收我有
@RequestMapping(value = "/details", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<Object> processUserdetails(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "details", required = true) final String studentDetail) {
logger.info("Mobile Student Signup > Message received: " + studentDetail);
}
但是服务器没有收到任何数据..为什么?
答案 0 :(得分:0)
尝试使用这种方式:
//Activity Class variable
StringBuilder sb; //don't forget to initialize it!
private class RegisterDevice extends AsyncTask<String,String,String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... strings) {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("FirstField", FirstValue));
nameValuePairs.add(new BasicNameValuePair("SecondField", SecondValue));
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(UrlHandler.vRegisterDevice);
httpPost.setHeader(HTTP.CONTENT_TYPE,"application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
//Log.e("Response: ", "" + reader.readLine());
if (sb != null) {
sb = null;
sb = new StringBuilder();
}
while ((sResponse = reader.readLine()) != null) {
sb = sb.append(sResponse);
}
Log.i("Test","doInBackground: " + sb.toString());
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
Log.d("Test","onPostExecute - Register Device");
String vResult = "";
if(sb != null)
vResult = sb.toString();
Log.d("Result String ",vResult);
if (vResult.contains("Success")) {//success
Intent intent = new Intent(CurrentAtivity.this,TargetActivity.class);
startActivity(intent);
//Hide the progress bar as the task done
ProgressBar.setVisibility(View.GONE);
}
}catch (Exception ex){
ex.printStackTrace();
}
}
}
答案 1 :(得分:0)
这是我使用openConnection方法进行Web服务的方式。这是使用get方法,但您可以相应地更改它。
@Override
protected Integer doInBackground(String... params) {
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
Integer result = 0;
try {
/* forming th java.net.URL object */
URL url = new URL(params[0]);
//String mobileNo = mobileno.getText().toString();
urlConnection = (HttpURLConnection) url.openConnection();
/* optional request header */
urlConnection.setRequestProperty("Content-Type", "application/json");
/* optional request header */
urlConnection.setRequestProperty("Accept", "application/json");
/* for Get request */
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
response = convertInputStreamToString(inputStream);
result = 1; // Successful
System.out.println(response);
} else {
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d("msg", e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
这是 convertInputStream 方法
private String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
inputStream.close();
return result;
}
这就是我传递网址的方式
JOBCOMPLETE_URL=Baseurl + "job_complete.php?cid="+userid;
CompletedJobAsyncTask completedJobAsyncTask=new CompletedJobAsyncTask();
completedJobAsyncTask.execute(JOBCOMPLETE_URL);