我是android新手,我做了一个活动,我必须发布一些参数来进行api调用并得到响应,我必须传递一些参数追加到请求url和其他像Json格式,请告诉我我该怎么办,我的示例网址请求如下:
和json体中的其他参数如下:
{
"destinations": [
{
"city_id": 1,
"start_date": "2014/08/28",
"end_date": "2014/09/30"
},
{
"city_id": 5,
"start_date": "2014/08/10",
"end_date": "2014/09/03"
}
]
}
答案 0 :(得分:2)
a。)上课并将你的网址分开 假设App_WebServiceUrls
public class App_WebServiceUrls {
public static String GetDetails ="http://dev.abctest.com/api/v1/book";
}
2.现在打电话给webservice / Web Api。 单独调用api调用或使用Asynctasks 所以要避免使用NetworkOnMainThredException。
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
// Add your data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair(customer_firstname, "Deepak"));
nameValuePair.add(new BasicNameValuePair(customer_lastname, "Panwar"));
JSONObject json = null;
try {
json = new JSONObject();
json = JsonParserHelper.makeHttpRequest(
App_WebServiceUrls.CompanyDivisions, "GET", nameValuePair);
Log.d("Division List Response:", "" + json);
if (json != null) {
}else
{
/**To print tost on ui thread**/
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
/**Write Toast here**/
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}).start();
用于进行webapi调用的/ 助手类 /
public class JsonParserHelper {
static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jArr = null;
static String json = "";
public static JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
try {
if (method == "POST") {
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
Log.v("Urltocheck", "" + url);
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
Log.v("Urltocheck", "" + url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
// jArr = new JSONArray(json);
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String (Array)
// return jArr;
return jObj;
}
}
答案 1 :(得分:1)
首先,您需要将网址字段附加到基本网址。然后,如果有任何字段,您可以添加可选字段。然后将您的数据作为HttpPost中的实体,其中url将是处理后获得的url。
请尝试以下操作:
要调用的父方法。
public void request(String baseUrl,List<NameValuePair> urlFields, List<NameValuePair> formData,List<NameValuePair> optionalData ){
// Append params to the URL
if (urlFields != null)
baseUrl = baseUrl + getUrlPathForGet(urlFields);
// adds Optional fields to the Url
if (optional != null)
baseUrl = baseUrl + "?" + URLEncodedUtils.format(optionalData, "utf-8");
postData(baseUrl,formData);
}
它会将url参数附加到基本网址
private String getUrlPathForGet(List<NameValuePair> urlFields) {
String path = "";
if (urlFields != null) {
for (NameValuePair pair : urlFields) {
path = path + "/" + pair.getValue();
}
}
return path;
}
使用修改后的网址将表单数据作为实体添加到HttpPost对象。
public void postData(String baseUrl,List<NameValuePair> formData) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
// pass the url as parameter and create HttpPost object.
HttpPost post = new HttpPost(baseUrl);
// Add header information for your request - no need to create
// BasicNameValuePair() and Arraylist.
post.setHeader("Authorization", "Bearer " + token);
post.setHeader("Content-Type", "application/json");
post.setHeader("Cache-Control", "no-cache");
try {
// pass the content as follows:
post.setEntity(new UrlEncodedFormEntity(formData,
HTTP.UTF_8));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(post);
// TODO: Process your response as you would like.
} catch (IOException e) {
// TODO Auto-generated catch block
}
}