我使用post方法将一个字节流发送到其余服务,如下所示:
h = httplib2.Http(".cache")
h.add_credentials("admin","admin")
data = urllib.urlencode({"packet":str(pack)})
resp, content = h.request(url, "POST", data)
后调用结果使用%
(data
编码)对字节流进行编码。现在我想要检索原始字节流。我在休息服务端(java)尝试了以下方式,但我无法检索原始字节流。
String pack_decode = java.net.URLDecoder.decode(packet, "UTF-8");
// I am expecting decoded byte stream (free from `%` encoding) but I am getting the same encoded string.
答案 0 :(得分:0)
你能发布完整的源代码吗?看来这应该有用,至少接下来工作正常:
客户端(Python):
# -*- coding: utf-8 -*-
import httplib2
import urllib
url = 'http://127.0.0.1:8000/test'
h = httplib2.Http(".cache")
pack = 'Источники в Кремле: вердикт Гааги по ЮКОСу не важен, потому что грядет война в Европе'
data = urllib.urlencode({"packet":str(pack)})
resp, content = h.request(url, "POST", data)
服务器(Java):
package com.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Server {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test", new Handler());
server.setExecutor(null);
server.start();
}
static class Handler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
InputStreamReader isr = new InputStreamReader(t.getRequestBody(),"utf-8");
BufferedReader br = new BufferedReader(isr);
int b;
StringBuilder buf = new StringBuilder(512);
while ((b = br.read()) != -1) {
buf.append((char) b);
}
br.close();
isr.close();
System.out.println("Encoded msg: \n" + buf);
String pack_decode = java.net.URLDecoder.decode(buf.toString(), "UTF-8");
System.out.println("Decoded msg: " + pack_decode);
}
}
}
服务器端的输出:
编码:
包=%D0%98%D1%81%D1%82%D0%BE%D1%87%D0%BD%D0%B8%D0%BA%D0%B8 +%D0%B2 +%D0%9A% D1%80%D0%B5%D0%BC%D0%BB%D0%B5%3A +%D0%B2%D0%B5%D1%80%D0%B4%D0%B8%D0%BA%D1%82 + %D0%93%D0%B0%D0%B0%D0%B3%D0%B8 +%D0%BF%D0%BE +%D0%AE%D0%9A%D0%9E%D0%A1%D1%83 +% D0%BD%D0%B5 +%D0%B2%D0%B0%D0%B6%D0%B5%D0%BD%2C +%D0%BF%D0%BE%D1%82%D0%BE%D0%BC% D1%83 +%D1%87%D1%82%D0%BE +%D0%B3%D1%80%D1%8F%D0%B4%D0%B5%D1%82 +%D0%B2%D0%BE% D0%B9%D0%BD%D0%B0 +%D0%B2 +%D0%95%D0%B2%D1%80%D0%BE%D0%BF%D0%B5
解码:
packet =ИсточникивКремле:вердиктГаагипоЮКОСуневажен,потомучтогрядетвойнавЕвропе