Php 在HTTPURLConnection上进行POST的简单方法?
在android上的AsyncTask中,在HTTPURLCONNECTION上发布最简单的方法是什么?Php 在HTTPURLConnection上进行POST的简单方法?,php,android,json,Php,Android,Json,在android上的AsyncTask中,在HTTPURLCONNECTION上发布最简单的方法是什么? 我只想在我的php文件上发布数据,然后返回一个json响应 class ImageUploadTask extends AsyncTask <Void, Void, String>{ @Override protected String doInBackground(Void... unsued) { try { HttpC
我只想在我的php文件上发布数据,然后返回一个json响应
class ImageUploadTask extends AsyncTask <Void, Void, String>{
@Override
protected String doInBackground(Void... unsued) {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(
getString(R.string.WebServiceURL)
+ "/cfc/iphonewebservice.cfc?method=uploadPhoto");
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("photoId", new StringBody(getIntent()
.getStringExtra("photoId")));
entity.addPart("returnformat", new StringBody("json"));
entity.addPart("uploaded", new ByteArrayBody(data,
"myImage.jpg"));
entity.addPart("photoCaption", new StringBody(caption.getText()
.toString()));
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse = reader.readLine();
return sResponse;
} catch (Exception e) {
if (dialog.isShowing())
dialog.dismiss();
Toast.makeText(getApplicationContext(),
getString(R.string.exception_message),
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
// (null);
}
你可以从我前几天给你的答案中拼凑出来: 。。。答案如下: 也就是说,开始发送POST数据并获得JSON结果的最简单方法就是使用旧的API 下面是一个工作示例:
class CreateNewProduct extends AsyncTask<String, String, JSONObject> {
InputStream is = null;
JSONObject jObj = null;
String json = "";
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ShareNewMessage.this);
pDialog.setMessage("Sharing Message...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
* */
protected JSONObject doInBackground(String... args) {
String message = inputMessage.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", username));
params.add(new BasicNameValuePair("message", message));
Log.d("Share", "Sharing message, username: " + username + " message: " + message);
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_create_message);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
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("Share", "Error converting InputStream result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("Share", "Error parsing JSON data " + e.toString());
}
try{
int success = jObj.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return jObj;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(JSONObject jObj) {
//do something with jObj
// dismiss the dialog once done
pDialog.dismiss();
}
}
class CreateNewProduct扩展了异步任务{
InputStream=null;
JSONObject jObj=null;
字符串json=“”;
/**
*在启动后台线程显示进度对话框之前
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(ShareNewMessage.this);
设置消息(“共享消息…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
/**
*创造产品
* */
受保护的JSONObject doInBackground(字符串…args){
字符串消息=inputMessage.getText().toString();
//建筑参数
List params=new ArrayList();
添加(新的BasicNameValuePair(“名称”,用户名));
添加(新的BasicNameValuePair(“消息”,消息));
Log.d(“共享”、“共享消息”,用户名:“+username+”消息:“+message”);
试一试{
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url\u创建\u消息);
setEntity(新的UrlEncodedFormEntity(参数));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
is,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
json=sb.toString();
}捕获(例外e){
Log.e(“共享”,“转换InputStream结果时出错”+e.toString());
}
//尝试将字符串解析为JSON对象
试一试{
jObj=新的JSONObject(json);
}捕获(JSONException e){
Log.e(“共享”,“解析JSON数据时出错”+e.toString());
}
试一试{
int success=jObj.getInt(TAG_success);
如果(成功==1){
//已成功创建产品
}否则{
//未能创建产品
}
}捕获(JSONException e){
e、 printStackTrace();
}
返回jObj;
}
/**
*完成后台任务后,关闭“进度”对话框
* **/
受保护的void onPostExecute(JSONObject jObj){
//对乔布做点什么
//完成后关闭对话框
pDialog.disclose();
}
}
试试这个
public class parseProduct extends AsyncTask<Void, Void, Void> {
String jsonResponse;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
JSONObject object = new JSONObject();
try {
object.put("registeruserid", userId); // you can pass data which you want to pass from POST
} catch (JSONException e) {
e.printStackTrace();
}
try {
jsonResponse=getResponseStringFromURL2(URL,object.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void resul) {
super.onPostExecute(resul);
}
}
你又一次帮了我。谢谢:)
public class parseProduct extends AsyncTask<Void, Void, Void> {
String jsonResponse;
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
JSONObject object = new JSONObject();
try {
object.put("registeruserid", userId); // you can pass data which you want to pass from POST
} catch (JSONException e) {
e.printStackTrace();
}
try {
jsonResponse=getResponseStringFromURL2(URL,object.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void resul) {
super.onPostExecute(resul);
}
}
public String getResponseStringFromURL2(String url, String json)
throws ClientProtocolException, IOException {
StringBuilder result = new StringBuilder();
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 30000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 30000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost request = new HttpPost(url);
if (json != null) {
StringEntity se = new StringEntity(json);
request.setEntity(se);
}
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
Log.d("request: ", ":" + request.getRequestLine());
HttpResponse response = null;
response = httpClient.execute(request);
if (response == null)
return null;
InputStream input = null;
input = new BufferedInputStream(response.getEntity().getContent());
byte data[] = new byte[40000];
int currentByteReadCount = 0;
/** read response from inpus stream */
while ((currentByteReadCount = input.read(data)) != -1) {
String readData = new String(data, 0, currentByteReadCount);
result.append(readData);
}
input.close();
return result.toString();
}