从服务器发送和获取数据不起作用

时间:2016-01-16 05:35:06

标签: android

我的android项目我想发送json数据(As Arraylist),带标题..

并将服务器响应读为字符串..

不推荐使用

DefaultHttpClient 。因此,我正在使用 HttpURLConnection ..

这是我的代码: -

@Override
public String Signup(String name, String phno) throws Exception {

  String url="http://address/AndroidProject/userSignup";

 // Instantiate and initialise a SignupForm
   Form suf = new Form(name, phno);

// store suf in a list
List<NameValuePair> pairs = new ArrayList<NameValuePair>(1);

// create the K,V to be sent
 pairs.add(new BasicNameValuePair("suf", new Gson().toJson(suf)));

 try
 {

 URL  url1 = new URL(url);
 HttpURLConnection connection = (HttpURLConnection) url1.openConnection();

//encoded pairs
 HttpEntity requestEntity = new UrlEncodedFormEntity(pairs);

 connection.setRequestMethod("POST");

//add header
 connection.setRequestProperty("Id", myId);

 connection.setDoOutput(true);

//send data
 OutputStreamWriter writer = 
       new OutputStreamWriter(connection.getOutputStream());

 writer.write(requestEntity.toString());
 writer.flush();
 connection.connect();


// read the output from the server
 String content =  connection.getResponseMessage();
 int responseCode = connection.getResponseCode();

// if response HttpStatus is not 'CREATED'
if (responseCode != 201) {

// throw the error message to the application

}

// we can return the authToken.
return content;

}
catch (Exception e)
{
e.printStackTrace();
 throw e;
}
}

我收到错误:

Server response string: Required String parameter 'suf' is not present
Signup access server error: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1

但是这段代码没有向服务器发送任何数据..问题是什么?为什么我不能发布值?我错过了什么?

0 个答案:

没有答案