0

我已经尝试了两周的大部分时间,我真的被困住了。最初,我创建了一个简单的 ObjectOutputStream 客户端 - 服务器程序 - 客户端是 Android 应用程序,但它不起作用(它读取连接但不读取对象)。

所以现在我很困惑我可以采取哪些其他方法来执行这个简单的任务?任何人都可以帮忙吗?

4

4 回答 4

0

您可以使用它来将实体发布到服务器:

    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)  

或者你可以发送一个带有 bytearray 的实体。

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 真的希望它可以帮助您了解向服务器发送数据的概述

于 2012-02-23T16:15:46.780 回答
0

您是否尝试过使用 post 方法的 URLConnection?:)

或获取方法如:

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();
于 2012-02-23T16:02:16.933 回答
0

您可以尝试使用 JSON 搅拌来发送数据。我们有很多关于如何使用 JSON 的资料,也有很多 api。JSONSimple 是我可以建议的。它真的很容易。

于 2012-02-23T16:03:17.867 回答
0

你为什么不试试这个:

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();
于 2012-02-23T16:04:08.090 回答