【发布时间】:2012-03-14 01:34:19
【问题描述】:
两周来我一直在尝试这个,但我真的被困住了。最初我创建了一个简单的 ObjectOutputStream 客户端 - 服务器程序 - 客户端是 Android 应用程序,但它不起作用(它读取连接而不是对象)。
所以现在我很困惑我可以采取哪些其他方法来执行这个简单的任务?谁能帮忙?
【问题讨论】:
-
对服务器有什么要求吗?否则我会考虑使用 HTTP 服务器并使用该协议来回发送数据。
两周来我一直在尝试这个,但我真的被困住了。最初我创建了一个简单的 ObjectOutputStream 客户端 - 服务器程序 - 客户端是 Android 应用程序,但它不起作用(它读取连接而不是对象)。
所以现在我很困惑我可以采取哪些其他方法来执行这个简单的任务?谁能帮忙?
【问题讨论】:
您可以使用它向服务器发布实体:
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(url);
postRequest.setEntity(entity);
try {
HttpResponse response = httpClient.execute(postRequest
);
String jsonString = EntityUtils.toString(response
.getEntity());
Log.v(ProgramConstants.TAG, "after uploading file "
+ jsonString);
return jsonString;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
实体可以是名称值对:
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("key1", value1));
nvps.add(new BasicNameValuePair("key2", value2));
Entity entity=new UrlEncodedFormEntity(nvps, HTTP.UTF_8)
或者你可以发送一个带有字节数组的实体。
Bitmap bitmapOrg=getBitmapResource();
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
MultipartEntity entity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE)
entity.addPart("file", new ByteArrayBody(data, "image/jpeg",
"file"));
如果您想将 json 发布到服务器:
请查看此链接How do I send JSon as BODY In a POST request to server from an Android application?
对于java对象的序列化和反序列化,我推荐https://sites.google.com/site/gson/gson-user-guide#TOC-Using-Gson
真的希望它可以帮助您了解向服务器发送数据的概述
【讨论】:
你为什么不试试这个:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
【讨论】:
您可以尝试使用 JSON 搅拌来发送数据。我们有很多关于如何使用 JSON 的资料,也有很多 api。 JSONSimple 是我可以建议的。真的很简单。
【讨论】:
您是否尝试过使用 post 方法的 URLConnection? :)
或者像这样的get方法:
String yourURL = "www.yourwebserver.com?value1=one&value2=two";
URL url = new URL(yourURL);
URLConnection connection = url.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
response = in.readLine();
【讨论】: